﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using BaiduRefresher.Properties;

namespace BaiduRefresher
{
    public partial class MainFrm : Form
    {
        List<string> ProxyList = new List<string>();
        private Thread WorkThread;
        private Thread ProxyThread;
        private Thread CheckThread;        
        UrlAccesserManager UAM;
        public MainFrm()
        {
            InitializeComponent();
            LoadSettings();
        }
        private void toolStripMenuItem_Show_Click(object sender, EventArgs e)
        {
            ShowForm();
        }
        private void toolStripMenuItem_Hide_Click(object sender, EventArgs e)
        {
            HideFrom();
        }
        private void toolStripMenuItem_Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void notifyIcon_CatSoul_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                HideFrom();
            }
            else
            {
                ShowForm();
            }
        }
        private void ShowForm()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        private void HideFrom()
        {
            this.Hide();
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        private void button_Start_Click(object sender, EventArgs e)
        {
            Regex RegNumber = new Regex("^[0-9]+$");
            Regex RegUrl = new Regex(@"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
            Match murl = RegUrl.Match(textBox_url.Text);
            Match mnum = RegNumber.Match(textBox_second.Text);
            if (murl.Success && mnum.Success)
            {
                progressBar1.StartAutoTurnBack(1, Convert.ToInt32(textBox_second.Text)*10);
                SaveSettings();
                SetLabel("开始刷新");
                button_Start.Enabled = false;
                button_Stop.Enabled = true;
                ProxyList = new List<string>();
                if (checkBox_Agent.Checked)
                {
                    if (ProxyThread != null)
                    {
                        ProxyThread.Abort();
                    }
                    ProxyThread = new Thread(new ThreadStart(SetProxy));
                    ProxyThread.IsBackground = true;
                    ProxyThread.Start();
                    SetLabel("代理获取中");
                }
                if (CheckThread != null)
                {
                    CheckThread.Abort();
                }
                CheckThread = new Thread(new ThreadStart(Check));
                CheckThread.IsBackground = true;
                CheckThread.Start();
            }
            else
            {
                toolTip1.Show("请检查网址或频率的格式", button_Start, 0, button_Start.Height);
            }
        }
        private void Check()
        {
            if (ProxyThread != null)
            {
                while (ProxyThread.ThreadState != ThreadState.Stopped)
                {
                    Thread.Sleep(100);
                }
            }
            if (WorkThread != null)
            {
                WorkThread.Abort();
            }
            SetLabel("开始访问");
            UAM = new UrlAccesserManager(ProxyList, textBox_url.Text, Convert.ToInt32(textBox_second.Text));
            WorkThread = new Thread(new ThreadStart(Work));
            WorkThread.IsBackground = true;
            WorkThread.Start();
        }
        private void Work()
        {
            while (!button_Start.Enabled && UAM.AvailableAc != 0)
            {
                DateTime begin = DateTime.Now;
                UAM.Start();
                SetLabel(String.Format("已访问{0}次", UAM.AccessTimes));
                DateTime end = DateTime.Now;
                TimeSpan ts = begin - end;
                if (ts.Milliseconds < Convert.ToInt32(textBox_second.Text) * 1000)
                {
                    Thread.Sleep(Convert.ToInt32(textBox_second.Text) * 1000 - ts.Milliseconds);
                }
            }

        }
        /// <summary>
        /// 获取可用代理，并写入Proxy.txt
        /// </summary>
        private void SetProxy()
        {
            UrlAccesser ua = new UrlAccesser("http://hi.baidu.com/天之幻都");
            ua.AccessByLocal();
            if (ua.Connected)
            {
                try
                {

                    ProxyList = GetProxy.GetProxyFromLocal();
                    foreach (string s in GetProxy.GetProxyFromProxyCN())
                    {
                        if (!ProxyList.Contains(s))
                        {
                            ProxyList.Add(s);
                        }
                    }
                    ProxyManager PMgr = new ProxyManager(ProxyList);
                    ProxyList = PMgr.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                if (ProxyList.Count > 0)
                {
                    try
                    {
                        string filepath = AppDomain.CurrentDomain.BaseDirectory + "Proxy.txt";
                        FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                        fs.Close();
                        using (StreamWriter sw = new StreamWriter(filepath, true, Encoding.GetEncoding("GB2312")))
                        {
                            for (int i = 0; i < ProxyList.Count; i++)
                            {
                                string NextLine = ProxyList[i];
                                sw.WriteLine(NextLine);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
            else
            {
                if (checkBox_Agent.Checked)
                {
                    checkBox_Agent.Checked = false;
                    MessageBox.Show("网络较差，自动取消代理模式。");
                }
            }
        }
        delegate void SetLabelCallBack(string text);
        private void SetLabel(string text)
        {
            if (label_statue.InvokeRequired)
            {
                SetLabelCallBack cb = new SetLabelCallBack(SetLabel);
                this.Invoke(cb, new object[] { text });
            }
            else
            {
                label_statue.Text = text;
            }
        }
        private void button_Stop_Click(object sender, EventArgs e)
        {
            SetLabel("停止中");
            button_Stop.Enabled = false;
            if (WorkThread != null)
            {
                WorkThread.Abort();
            }
            if (ProxyThread != null)
            {
                ProxyThread.Abort();
            }
            if (CheckThread != null)
            {
                CheckThread.Abort();
            }            
            string s = "停止刷新";
            if (UAM != null)
            {
                s += "，" + String.Format("已访问{0}次", UAM.AccessTimes);
            }
            SetLabel(s);
            button_Start.Enabled = true;
            progressBar1.StopAutoTurnBack();
            progressBar1.Value = 0;
        }
        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            notifyIcon_CatSoul.Visible = false;
            this.Visible = false;
            if (WorkThread != null)
            {
                WorkThread.Abort();
            }
            if (ProxyThread != null)
            {
                ProxyThread.Abort();
            }
            if (CheckThread != null)
            {
                CheckThread.Abort();
            }            
        }
        private void SaveSettings()
        {
            Settings.Default.Url = textBox_url.Text;
            Settings.Default.Cycle = Convert.ToInt32(textBox_second.Text);
            Settings.Default.UseProxy = checkBox_Agent.Checked;
            Settings.Default.Save();
        }
        private void LoadSettings()
        {
            textBox_url.Text = Settings.Default.Url;
            textBox_second.Text = Settings.Default.Cycle.ToString();
            checkBox_Agent.Checked = Settings.Default.UseProxy;
        }
        private void 唔睇你蚀本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox_Other ab = new AboutBox_Other();
            ab.ShowDialog(this);
        }
        private void 使用说明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox_Operation ab = new AboutBox_Operation();
            ab.ShowDialog(this);
        }
    }
}
